package com.dahua.messageconsumer;

import com.dahua.common.domain.EquipmentStatus;
import com.dahua.common.domain.SensorData;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class EquipmentStatusCalculator {
    private final List<Field> fieldsToSum = new ArrayList<>();
    private EquipmentStatus sum;

    public EquipmentStatusCalculator() {
        final Field[] fields = SensorData.class.getDeclaredFields();
        final String fieldNamePatternToSum = "Period|TotalTimes|EndTime";
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getName().matches(fieldNamePatternToSum)) {
                fieldsToSum.add(field);
            }
        }
    }

    public void reset() {
        sum = null;
    }

    public void add(EquipmentStatus eqStatus) {
        if (sum == null) {
            sum = new EquipmentStatus();
        }

        for (Field field : fieldsToSum) {
            try {
                if (field.getType() == LocalDateTime.class) {
                    field.set(sum, field.get(eqStatus));
                    continue;
                }
                Integer data = (Integer) field.get(eqStatus);
                Integer sumData = (Integer) field.get(sum);
                if (data == null) {
                    continue;
                }
                if (sumData != null) {
                    sumData = sumData + data;
                    field.set(sum, sumData);
                } else {
                    field.set(sum, data);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void writeSum(EquipmentStatus equipmentStatus) {
        Objects.requireNonNull(sum, "sum is null");
        Objects.requireNonNull(equipmentStatus, "equipmentStatus is null");

        for (Field field : fieldsToSum) {
            try {
                field.set(equipmentStatus, field.get(sum));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
